package com.dmy.common.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.util.Arrays;

/**
 * create by YCQ for 2020/1/8 13:18
 */
public class HanyuPinyinUtil {
    private static final HanyuPinyinOutputFormat HANYU_PINYIN_OUTPUT_FORMAT= new HanyuPinyinOutputFormat();
    static {
        HANYU_PINYIN_OUTPUT_FORMAT.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        HANYU_PINYIN_OUTPUT_FORMAT.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
    }
    public static final String hanziToPinyin(Character character) throws BadHanyuPinyinOutputFormatCombination {
        if(character==null){
            return null;
        }
        if(Character.isLetter(character)){
            return character.toString();
        }

        String[] array = PinyinHelper.toHanyuPinyinStringArray(character, HANYU_PINYIN_OUTPUT_FORMAT);
        return array==null || array.length == 0 ? null:array[0];
    }
    public static final boolean isHanZi(Character character){
        if(character == null){
            return false;
        }
        return character.toString().matches("[\\u4E00-\\u9FA5]+");
    }

    public static void main(String[] args) throws BadHanyuPinyinOutputFormatCombination {
        System.out.println(HanyuPinyinUtil.isHanZi('是'));
        System.out.println(HanyuPinyinUtil.hanziToPinyin('是'));
        System.out.println(HanyuPinyinUtil.hanziToPinyin('是').substring(0,1).toUpperCase());
    }
}
